//
//  TextAttachmentContainer.swift
//  LibUI
//
//  Created by ChangtanSun on 2017/6/1.
//  Copyright © 2017年 ChangtanSun. All rights reserved.
//

import UIKit
import Foundation

/// 自定义TextAttachment
public extension NSAttributedString.Key {
    static let textLink = NSAttributedString.Key("LinkAttributeName")

    static let textAttachment = NSAttributedString.Key("TextAttachmentAttributeName")
}

/// 自定义TextAttachment字符
let TextAttachmentCharacter = "\u{FFFC}"

/// 自定义TextAttachment协议，实现该协议自定义NSAttributedString绘制方式
public protocol TextAttachmentContainer {
    func drawAttachment(context: CGContext, textAttachmentBounds: CGRect, textContainer: NSTextContainer, characterIndex: Int)

    func attachmentBounds(for textContainer: NSTextContainer?, proposedLineFragment lineFrag: CGRect, glyphPosition position: CGPoint, characterIndex charIndex: Int) -> CGRect

    func layoutManager(_ layoutManager: NSLayoutManager, shouldSetLineFragmentRect lineFragmentRect: UnsafeMutablePointer<CGRect>, lineFragmentUsedRect: UnsafeMutablePointer<CGRect>, baselineOffset: UnsafeMutablePointer<CGFloat>, in textContainer: NSTextContainer, forGlyphRange glyphRange: NSRange) -> Bool

    func layoutManager(_ layoutManager: NSLayoutManager, lineSpacingAfterGlyphAt glyphIndex: Int, withProposedLineFragmentRect rect: CGRect) -> CGFloat
}

public extension NSAttributedString {
    convenience init(textAttachment: TextAttachmentContainer) {
        self.init(string: TextAttachmentCharacter, attributes: [NSAttributedString.Key.textAttachment: textAttachment])
    }
}
